package com.woniuxy.tfss.jwt;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.tfss.entity.Admin;
import com.woniuxy.tfss.entity.Perms;
import com.woniuxy.tfss.entity.RolePerm;
import com.woniuxy.tfss.service.AdminService;
import com.woniuxy.tfss.service.PermsService;
import com.woniuxy.tfss.service.RolePermService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class JwtRealm extends AuthorizingRealm {
    private static final Logger log = LoggerFactory.getLogger(JwtRealm.class);
    @Autowired
    private AdminService adminService;
    @Autowired
    private RolePermService rolePermService;
    @Autowired
    private PermsService permsService;
    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取该用户的权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        String account = (String) principals.getPrimaryPrincipal(); //账号
        //ResponseEntity<ResponseEntity> responseEntity = restTemplate.getForEntity(server + "/getpermsbyaccount/" + account, ResponseEntity.class);
        QueryWrapper<Admin> wrapper=new QueryWrapper<>();
        wrapper.eq("account",account);
        Admin admin=adminService.getOne(wrapper);
        QueryWrapper wrapper1=new QueryWrapper();
        wrapper1.eq("roleId",admin.getRoleId());
        List<RolePerm> rolePerms= rolePermService.list(wrapper1);
        QueryWrapper<Perms> wrapper2=new QueryWrapper<>();
        rolePerms.forEach(r->{
            wrapper2.or().eq("id",r.getPermId());
            wrapper2.eq("type","a");
        });
        List<Perms> perms=permsService.list(wrapper2);
        perms.forEach(d -> {
            info.addStringPermission(d.getIdentity());
            log.debug("用户权限;{}",d.getIdentity());
        });
     return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String account = (String) token.getPrincipal();
        QueryWrapper<Admin> wrapper=new QueryWrapper<>();
        wrapper.eq("account",account);
        Admin admin=adminService.getOne(wrapper);
        if (admin == null) {
            //账号不存在异常
            throw new UnknownAccountException();
        }else if(Admin.LOCKED.equals(admin.getStatus())){
            //账号被冻结异常
            throw new DisabledAccountException();
        }
        SecurityUtils.getSubject().getSession().setAttribute("adminId", admin.getId());
        ByteSource salt = ByteSource.Util.bytes(admin.getAccount());
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin.getAccount(), admin.getPassword(),salt, "realm");
        return info;
    }
    }

